package com.zcsy.manage.web.mall;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.ShopInfo;
import com.zcsy.manage.model.mall.GoodsCategory;
import com.zcsy.manage.model.mall.GoodsInfo;
import com.zcsy.manage.model.mall.OrderDetailInfo;
import com.zcsy.manage.model.mall.OrderDetailInfoView;
import com.zcsy.manage.model.mall.OrderInfo;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.mall.IGoodsCategoryService;
import com.zcsy.manage.service.mall.IGoodsInfoService;
import com.zcsy.manage.service.mall.IOrderDetailInfoService;
import com.zcsy.manage.service.mall.IOrderInfoService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;
import com.zcsy.manage.web.tools.JExcelReport;

/**
 * 
 * @Title: OrderInfoController.java
 * @Package： com.zcsy.manage.web.mall 
 * @Description: 订单控制层
 * @author zhangsh zsh3384027@gmail.com
 * @Copyright: 2016 武汉恒数利通技术有限公司 All rights reserved.
 * @date 2016年4月25日
 * @version 1.0
 * @see JDK1.8.0_45
 * @since
 */
@Controller
@RequestMapping(value= "/orderInfo")
public class OrderInfoController {
	
	@Autowired
	private IOrderInfoService orderInfoService;
	
	@Autowired
	private IOrderDetailInfoService orderDetailInfoService;
	//商铺信息
	@Autowired
	private IShopInfoService shopInfoService;
	//商品信息
	@Autowired
	private IGoodsInfoService goodsInfoService;
	//商品分类信息
	@Autowired
	private IGoodsCategoryService goodsCategoryService;

	@Autowired
	private IDictService dictService;
	
	/**
	 * 
	 * @Description 订单分页数据获取
	 * @param model
	 * @param pNo
	 * @param orderNumber
	 * @param beginDate
	 * @param endDate
	 * @param state
	 * @param req
	 * @return 
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月28日
	 * @see
	 */
	@RequestMapping(value = "/orderInfoList", method=RequestMethod.GET)
	public String orderInfoList(Model model, Integer pNo, Integer pSize, String orderNumber,
			String beginDate, String endDate,Integer state, HttpServletRequest req) {
		if(pNo == null){
    		pNo = Constants.PAGE_NO;
    	}

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        OrderInfo orderInfo = new OrderInfo();
        
        //获取当前小区id
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        
        if (StringUtils.isNotEmpty(orderNumber)) {
        	orderInfo.setOrderNumber(orderNumber);
		}
        if (StringUtils.isNotEmpty(beginDate)) {
        	orderInfo.setBeginTime(beginDate);
        }
        if (StringUtils.isNotEmpty(endDate)) {
        	orderInfo.setEndTime(endDate);
        }
        if (state == null) {
            state = Constants.SELECT_NONE;
        }
        orderInfo.setState(state);
        orderInfo.setCellId(cellId);
        //此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);
        List<OrderInfo> list = orderInfoService.selectByKeywordCommand(orderInfo);
        PageInfo<OrderInfo> unit = new PageInfo<OrderInfo>(list);
        
        if (list.size() >= 1) {
			List<OrderDetailInfoView> orderDetailInfoList = orderDetailInfoService.getByOrderId(list.get(0).getId());
			  model.addAttribute("orderDetailInfoList",orderDetailInfoList);
		}
        
        model.addAttribute("orderInfos",unit);
        model.addAttribute("currentPage",pNo);
		model.addAttribute("pSize", pSize);
        model.addAttribute("orderNumber", orderNumber);
        model.addAttribute("beginDate", beginDate);
        model.addAttribute("endDate", endDate);
        model.addAttribute("state", state);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

		return "mall/orderinfo/orderinfoList";
	}
	
	/**
	 * 
	 * @Description 订单商品详细信息
	 * @param model
	 * @param orderDetailId
	 * @param req
	 * @return 
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月28日
	 * @see
	 */
	@RequestMapping(value= "/orderGoodsDetailInfo", method=RequestMethod.GET)
	public String goodsInfoList(Model model,String orderDetailId,HttpServletRequest req){
		
		OrderDetailInfo orderDetailInfo = orderDetailInfoService.selectByPrimaryKey(orderDetailId);
		GoodsInfo goodsInfo = goodsInfoService.getGoodsInfoByPrimaryKey(orderDetailInfo.getGoodsId());
//		OrderInfo orderInfo = orderInfoService.selectOrderByPrimaryKey(orderDetailInfo.getOrderId());
		ShopInfo shopInfo = shopInfoService.selectByPrimaryKey(orderDetailInfo.getShopId());
		GoodsCategory goodsCategory = goodsCategoryService.getGoodsCategoryById(goodsInfo.getGoodsCategoryId());
		
//		model.addAttribute("orderInfo",orderInfo);
		model.addAttribute("goodsCategory",goodsCategory);
		model.addAttribute("shopInfo",shopInfo);
		model.addAttribute("orderDetailInfo",orderDetailInfo);
		model.addAttribute("goodsInfo",goodsInfo);
		
		
		return "mall/orderinfo/orderGoodsDetailInfo";
	}
	
    /**
     * @Description 订单详细情况
     * @author zhangsh zsh3384027@gmail.com
     * @date 2016年4月29日
     * @see
     */
    @RequestMapping(value = "/orderDetailInfo", method = RequestMethod.GET)
    public String orderDetail(Model model, String orderId, HttpServletRequest req) {
        OrderInfo orderInfo = orderInfoService.selectOrderByPrimaryKey(orderId);
        List<OrderDetailInfoView> orderDetailInfoList = orderDetailInfoService.getByOrderId(orderInfo.getId());

        model.addAttribute("orderInfo", orderInfo);
        model.addAttribute("orderDetailInfoList", orderDetailInfoList);

        return "mall/orderinfo/orderinfoDetail";
    }

    /**
     * @description 导出订单列表
     * @author chenxin
     * @date 2016年8月17日下午7:41:49
     */
    @RequestMapping("/exportOrderListExcel")
    @ResponseBody
    public void exportOrderListExcel(HttpServletResponse response,String orderNumber,
            String beginDate, String endDate,Integer state, HttpServletRequest request) {
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

        OrderInfo orderInfo = new OrderInfo();
        if (StringUtils.isNotEmpty(orderNumber)) {
            orderInfo.setOrderNumber(orderNumber);
        }
        if (StringUtils.isNotEmpty(beginDate)) {
            orderInfo.setBeginTime(beginDate);
        }
        if (StringUtils.isNotEmpty(endDate)) {
            orderInfo.setEndTime(endDate);
        }
        if (state == null) {
            state = Constants.SELECT_NONE;
        }
        orderInfo.setState(state);
        try {
            // 得到导出的数据列表
            List<OrderInfo> list = orderInfoService.selectByKeywordCommand(orderInfo);

            // 将订单对象转化为到处所需要的数据格式
            if (list.size() > 0) {
                ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();
                int index = 1;
                for (OrderInfo orderInformation : list) {
                    ArrayList<String> temp = new ArrayList<String>();
                    // 序号
                    temp.add(String.valueOf(index++));
                    temp.add(orderInformation.getId());
                    temp.add(orderInformation.getOrderNumber());
                    temp.add(orderInformation.getFinalPrice().toString());
                    temp.add(orderInformation.getUserAccount());
                    temp.add(orderInformation.getType().toString());
                    temp.add(orderInformation.getState().toString());
                    temp.add(orderInformation.getContactor());
                    temp.add(orderInformation.getContactorPhone());
                    temp.add(DateUtils.formatDate(orderInformation.getCreateTime()));
                    dataList.add(temp);
                }
                // 导出标题列
                String[] rows = new String[] { "序号", "订单号", "订单总金额", "用户号", "订单类型", "订单状态", "联系人", "联系电话",
                        "创建时间" };
                // 导出excel文件每列宽度
                int[] style = new int[] { 5, 20, 20, 20, 20, 20, 20, 20, 20};
                // Excel文件sheet名称
                String sheetName = "订单清单" + DateUtils.getCurrentDate();
                String fileName = "订单清单";
                doExecl(response, fileName, sheetName, dataList, rows, style);
                LogUtils.insertLog("用户导出订单列表", user.getId(), request);
                
            }
        } catch (Exception e) {
            return;
        }
    }
    
    /**
     * @Description 通过传入的对象信息集合产生的excel表格<br>
     * @param response
     *            用户响应
     * @param sheetName
     *            excel表名称
     * @param dataList
     *            传入的数据列表
     * @param rows
     *            excel表的列控制，名称
     * @param style
     *            规定列宽等样式
     * @throws Exception
     * @author xujl
     * @date 2016年5月3日
     * @see
     */
    private void doExecl(HttpServletResponse response, String tempName, String sheetName,
                         ArrayList<ArrayList<String>> dataList, String[] rows, int[] style)
        throws Exception {
        // 输出的excel名称为中文，否则发生错误
        String tempFileName = tempName + ".xls";
        String fileName = new String(tempFileName.getBytes("GB2312"), "ISO_8859_1");

        ServletOutputStream fout = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "filename=" + fileName + "");
        JExcelReport jexcelOutStream = new JExcelReport();
        try {
            jexcelOutStream.excelreport(sheetName, dataList, rows, fout, style);
            fout.flush();
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
    /**
     * @Description:积分商品和秒杀商品由平台直接发货
     * @param orderInfoId 订单id
     * @author huangls 1449700087@qq.com
     * @date 2016年9月12日
     */
    @RequestMapping(value="/sendGoods" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson sendGoods(Model model, String orderInfoId, HttpServletRequest req){
    	
    	RequestJson result = new RequestJson();
    	User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
    	OrderInfo orderInfo = orderInfoService.selectByPrimaryId(orderInfoId);
    	
    	//运营中心发货时间
    	Date sendGoodsTime = new Date();
    	try{
    		if(orderInfoId != null) {
    			
    			 if(orderInfo.getSenderAccount() != null) {
    				 
    				 orderInfo.setState(Constants.ORDER_DISTRIBUTION_ING);
    				 orderInfo.setSendTime(sendGoodsTime);
    				 orderInfo.setSendAccount(user.getLoginname());
    				 orderInfoService.update(orderInfo);
    				 result.setSuccess(true);
    				 result.setMsg("操作成功");
    				 
    			 }  else {
    	        	  result.setSuccess(false);
    	        	  result.setMsg("无配送人员，无法发货！");
    	          }
    		}
    		
    	} catch (Exception e) {
            e.printStackTrace();
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
    	return result;
    }
    
    /**
     * @Description:由运营中心确认退款完成
     * @param orderInfoId 订单id
     * @author huangls 1449700087@qq.com
     * @date 2016年9月12日
     */
    @RequestMapping(value="/completeRefund" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson completeRefund(Model model, String orderInfoId, HttpServletRequest req){
    	
    	RequestJson result = new RequestJson();
    	User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
    	OrderInfo orderInfo = orderInfoService.selectByPrimaryId(orderInfoId);
    	
    	//运营中心完成退款时间
    	Date completeRefundTime = new Date();
    	try{
    		if(orderInfoId != null) {
	    		orderInfo.setState(Constants.ORDER_REFUND_DONE);
	    		orderInfo.setRefundSuccessTime(completeRefundTime);
	    		orderInfo.setRefundSuccessAccount(user.getLoginname());
		    	orderInfoService.update(orderInfo);
		    	result.setSuccess(true);
    		}
    		
    	} catch (Exception e) {
            e.printStackTrace();
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
    	return result;
    }
    
    /**
     * @Description:由运营中心确认退货完成
     * @param orderInfoId 订单id
     * @author huangls 1449700087@qq.com
     * @date 2016年9月12日
     */
    @RequestMapping(value="/completeReturn" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson completeReturn(Model model, String orderInfoId, HttpServletRequest req){
    	
    	RequestJson result = new RequestJson();
    	User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
    	OrderInfo orderInfo = orderInfoService.selectByPrimaryId(orderInfoId);
    	
    	//运营中心完成退货时间
    	Date completeReturnTime = new Date();
    	try{
    		if(orderInfoId != null) {
	    		orderInfo.setState(Constants.ORDER_RETURN_DONE);
	    		orderInfo.setReturnSuccessTime(completeReturnTime);
	    		orderInfo.setReturnSuccessAccount(user.getLoginname());
		    	orderInfoService.update(orderInfo);
		    	result.setSuccess(true);
    		}
    		
    	} catch (Exception e) {
            e.printStackTrace();
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
    	return result;
    }
    
}
